package com.zoe.onelink.business.param;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.resource.ResourceUtil;
import com.alibaba.fastjson.JSON;
import com.zoe.onelink.business.cache.bean.SysParam;
import com.zoe.onelink.business.dao.ParamDao;
import com.zoe.onelink.enhancer.init.AbstractApplicationInitializer;
import com.zoe.onelink.util.StrUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.event.ApplicationStartedEvent;

import java.net.URL;
import java.util.List;

/**
 * <p>标题: </p>
 * <p>描述: </p>
 * <p>版权: Copyright (c) 2021</p>
 * <p>公司: 智业软件股份有限公司</p>
 *
 * @version: 1.0
 * @author: ruansheng
 * @date: 2021-12-07
 */
@Slf4j
@RequiredArgsConstructor
public class BizParamInitializer extends AbstractApplicationInitializer {

    private final ParamDao paramDao;

    @Override
    protected void doInit(ApplicationStartedEvent event) throws Exception {
        this.saveGlobalParam();
    }

    private void saveGlobalParam() {
        URL globalParamUrl = ResourceUtil.getResource("init/database/params-global.json");
        if (globalParamUrl == null) {
            return;
        }
        String paramJson = FileUtil.readUtf8String(globalParamUrl.getFile());
        List<SysParam> sysParams = JSON.parseArray(paramJson, SysParam.class);
        if (sysParams == null) {
            return;
        }
        for (SysParam sysParam : sysParams) {
            if (this.paramDao.getGlobalParam(sysParam.getParamEnglishName()) != null) {
                continue;
            }
            if (StrUtil.hasBlank(sysParam.getParamEnglishName(), sysParam.getParamValue())) {
                log.warn("[全局参数初始化] 参数名或参数值为空,已自动跳过. Param: {}", JSON.toJSONString(sysParam));
                continue;
            }
            this.paramDao.insertGlobalParam(sysParam);
            log.info("[全局参数初始化] 新增全局参数: {}", JSON.toJSONString(sysParam));
        }
    }


    @Override
    public boolean isAsync() {
        return false;
    }

    @Override
    public String eventName() {
        return "全局参数";
    }

    @Override
    public boolean throwable() {
        return false;
    }

}
